﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using TiTi.tea.Comm;
using TiTi.tea.DAL;
using TiTi.tea.Model;
using TiTi.tea.Dto;

namespace TiTi.tea.BLL
{
    public class MenuBLL
    {
        private MenuDAL dal=new MenuDAL();
        public IEnumerable<MenuInfo> Query(string MenuName,out int Total, int PageIndex,int PageSize)
        {
            var page = new PagePara(PageSize,PageIndex);
            if (string.IsNullOrEmpty(MenuName))
            {
                MenuName = "";
            }
            
            var data = dal.GetAll(o => o.MenuName.Contains(MenuName)&&o.IsDelete==0, o => o.CreateTime, page);
            Total=page.Total;
            return data;
        }

        /// <summary>
        /// 获取菜单树
        /// </summary>
        /// <returns></returns>
        public IEnumerable<MenuDto> GetAll()
        {
            var data = dal.GetAll(o=>o.IsDelete==0);

            var parent = data.Where(o=>o.PId==0).ToList();

            return parent.Select(o => new MenuDto()
            {
                Id = o.Id,
                MenuName = o.MenuName,
                MenuIcon = o.MenuIcon,
                MenuUrl = o.MenuUrl,
                Children = data.Where(c=>c.PId==o.Id).Select(c=>new MenuDto() { 
                    Id=c.Id,
                    MenuName = c.MenuName,
                    MenuIcon = c.MenuIcon,
                    MenuUrl = c.MenuUrl
                }).ToList()
            });
        }

        public MenuInfo GetOne(int Id)
        {
            return dal.GetOne(o => o.Id == Id);
        }

        public bool Add(MenuInfo info)
        {
            info.PId = info.PId ?? 0;
            info.CreateTime = DateTime.Now;
            info.MenuOrder=dal.GetAll().Max(o=>o.MenuOrder)+1;
            info.IsDelete = 0;
            return dal.Add(info);
        }

        public IEnumerable<MenuInfo> FuQuery() 
        {
            return dal.GetAll(o=>o.PId==0);
        }

        public bool Update(MenuInfo info)
        {
            return dal.Update(info);
        }
        
    }

}
